<?php
/**
 * 定时检测订单预警时间
 * Created by PhpStorm.
 * User: poptser
 * Email: poptser@foxmail.com
 * Date: 2016/8/25
 * Time: 16:52
 */

namespace SDXApi\Controller;
use SDXApi\Service\GoodsPriceTagService;
use Think\Controller;
use Think\Model;

class SystemalarmcheckController extends Controller
{
    public $pagesize=1000;
    
    
    /*
     * 下载导出货架列表详细信息数据
     * */
    public function export_shelves_data(){
        $f_head_arr = array(
            "货架商品编号ID", "货号","货架编号","货架商品所在列号"
            //"货架ID","货架编号","一共列数","商品种类数"
        );
        //-/ 请求头部设置
        $title=date('Y-m-d',time()).'-'.date('His',time());
        $file_name = 'All-shelves-Goods'.$title;
        $dirname=date('Y-m-d');
        $targetFolder='/Public/allgoodsshelvesxls/'.$dirname.'/';
        if (!file_exists($_SERVER['DOCUMENT_ROOT'].'/Public')||!is_dir($_SERVER['DOCUMENT_ROOT'].'/Public')){
            mkdir($_SERVER['DOCUMENT_ROOT'].'/Public',0777,true);
        }
        $firstLetterDir=$_SERVER['DOCUMENT_ROOT'].'/Public/allgoodsshelvesxls/';
        if (!file_exists($firstLetterDir)||!is_dir($firstLetterDir)){
            mkdir($firstLetterDir,0777,true);
        }
        if (!file_exists($firstLetterDir.'/'.$dirname)||!is_dir($firstLetterDir.'/'.$dirname)){
            mkdir($firstLetterDir.'/'.$dirname,0777,true);
        }
        $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
        $filename=$file_name.'.csv';
        $targetFile = rtrim($targetPath,'/') . '/' .$filename ;
        $file=fopen($targetFile, "wb");
        if(is_file($file)){
            returnApiError('fopen error!');
        }
        foreach ( $f_head_arr as $fkey=>$fval ){
            $f_head_arr[$fkey] = iconv('utf-8', 'gbk', $fval);
        }
        fputcsv($file, $f_head_arr);
        
        $sql='SELECT id,shelves_sn ,s_floor, COUNT(num) AS num'.
             ' FROM(SELECT s.shelves_sn,s.id,s.s_floor,COUNT(gs.goods_sn) AS num  FROM sdx_goods_storage as gs'.
             ' LEFT JOIN sdx_shelves_goods as sg ON gs.goods_sn=sg.goods_sn'.
             ' LEFT JOIN sdx_shelves as s ON s.id=sg.sh_id AND s.wid=8'.
             ' WHERE gs.wid=8 AND s.shelves_sn!=""'.
             ' GROUP BY s.id,sg.goods_sn) as u GROUP BY shelves_sn';
        $data=M()->query($sql);
        if($data){
            $shelves_goods_mod=M('shelves_goods');
            foreach ($data as $k=>$v){
                $sgdata=$shelves_goods_mod->where(array('sh_id'=>$v['id']))->group('sh_floor')->select();
                if($sgdata){
                    $sgarr=array();
                    foreach ($sgdata as $key=>$val){
                        $temp_arr=array();
                        $sgarr[]=(int)$val['sh_floor'];
                        $temp_arr['id']=iconv('utf-8', 'gbk', $val['id']);
                        $temp_arr['goods_sn']=iconv('utf-8', 'gbk', "'".$val['goods_sn']);
                        $temp_arr['shelves_sn']=iconv('utf-8', 'gbk',$v['shelves_sn'].'-'.$val['sh_floor']);
                        $temp_arr['sh_floor']=iconv('utf-8', 'gbk', $val['sh_floor']);
                        fputcsv($file, $temp_arr);
                        unset($temp_arr);
                    }
                    unset($sgdata);
                    for ($j=1;$j<=(int)$v['s_floor'];$j++){
                        $temp_arr=array();
                        if(!in_array($j, $sgarr,true)){
                            $temp_arr['id']=iconv('utf-8', 'gbk', '');
                            $temp_arr['goods_sn']=iconv('utf-8', 'gbk', '');
                            $temp_arr['shelves_sn']=iconv('utf-8', 'gbk',$v['shelves_sn'].'-'.$j);
                            $temp_arr['sh_floor']=iconv('utf-8', 'gbk', '');
                            fputcsv($file, $temp_arr);
                            unset($temp_arr);
                        }
                    }
                    unset($sgarr);
                }
            }
            unset($data);
            $files=$this->folder_list($targetPath, 'csv');
            $count=count($files);
            if($count>0){
                $this->download_file($files[$count-1]);
            }else{
                returnApiError('无下载数据');
            }
            ob_flush();
            flush();
            
        }
    }
    
   /*
    * 自动检测花城汇体验店仓库未绑定货架商品,并且删除的时候对应生成操作记录
    * */
    public function auto_check_goods_no_shelves (){
        set_time_limit(0);
        $sql='SELECT `goods_id`  FROM `sdx_goods` WHERE `goods_id` IN (SELECT goods_id   FROM `sdx_goods_storage` WHERE wid=8 and  `goods_sn` NOT IN (SELECT
			goods_sn
		FROM
			sdx_shelves_goods,
			sdx_shelves
		WHERE
			sdx_shelves.id = sdx_shelves_goods.sh_id
		AND sdx_shelves.wid = 8
		GROUP BY
			sdx_shelves_goods.goods_sn)) AND `is_delete` = 0';
        /*$gsdata=M('goods_storage')->alias('gs')
                 ->field('gs.goods_id,gs.goods_name,gs.goods_sn,s.shelves_sn,sg.sh_floor')
                 ->join('left join '.C ( 'DB_PREFIX' ).'shelves_goods as sg ON gs.goods_sn=sg.goods_sn')
                 ->join('left join '.C ( 'DB_PREFIX' ).'shelves as s ON s.id=sg.sh_id AND s.wid=8')
                 ->where('gs.wid=8 and ISNULL(s.shelves_sn) AND ISNULL(sg.sh_floor)')
                 ->select();*/
        $gsdata=M()->query($sql);
         if($gsdata){
             $goods_mod=M('goods');
             $goods_idarr=array();
             foreach ($gsdata as $k=>$v){
                 $goods_idarr[]=$v['goods_id'];
             }
             if(count($goods_idarr)>0){
                 $goods_ids=implode(',',$goods_idarr);
                 $where['goods_id']=array('in',$goods_ids);
                 $goods_save=$goods_mod->where($where)->save(array('is_delete'=>1));
                 if($goods_save!==false){
                     $goods_action_mod=M('goods_action');
                     foreach ($goods_idarr as $key=>$val){
                         $gaction_data=array(
                             'goods_id'=>$val,
                             'action_user'=>'系统脚本',
                             'action_time'=>gmtime(),
                             'action_type'=>'商品删除',
                             'old_value'=>'',
                             'new_value'=>''
                         );
                         $goods_action_mod->add($gaction_data);
                     }
                 }
             }
         }else{
             returnApiError('没有未绑定货架商品数据');
         }
    }
    
    /*
     * 指定商品ID批量还原已删除的商品
     * */
    public function auto_goods_delete_restore(){
        set_time_limit(0);
        $goods_ids=I('request.goods_ids');
        $no_shelves=I('request.no');
        if(empty($goods_ids) && !empty($no_shelves)){
            $gsdata=M('goods_storage')->alias('gs')
            ->field('gs.goods_id')
            ->join('left join '.C ( 'DB_PREFIX' ).'shelves_goods as sg ON gs.goods_sn=sg.goods_sn')
            ->join('left join '.C ( 'DB_PREFIX' ).'shelves as s ON s.id=sg.sh_id AND s.wid=8')
            ->where('gs.wid=8 and ISNULL(s.shelves_sn) AND ISNULL(sg.sh_floor)')
            ->select();
            if($gsdata){
                $goods_mod=M('goods');
                $goods_idarr=array();
                foreach ($gsdata as $k=>$v){
                    $goods_idarr[]=$v['goods_id'];
                }
                if(count($goods_idarr)>0){
                    $goods_ids=implode(',',$goods_idarr);
                    $where['goods_id']=array('in',$goods_ids);
                    $goods_save=$goods_mod->where($where)->save(array('is_delete'=>0));
                    if($goods_save!==false){
                        $goods_action_mod=M('goods_action');
                        foreach ($goods_idarr as $key=>$val){
                            $gaction_data=array(
                                'goods_id'=>$val,
                                'action_user'=>'系统脚本',
                                'action_time'=>gmtime(),
                                'action_type'=>'商品还原',
                                'old_value'=>'',
                                'new_value'=>''
                            );
                            $goods_action_mod->add($gaction_data);
                        }
                    }
                }
            }
        }else{
            $goods_mod=M('goods');
            $where['goods_id']=array('in',$goods_ids);
            $goods_save=$goods_mod->where($where)->save(array('is_delete'=>0));
            if($goods_save!==false){
                $goods_action_mod=M('goods_action');
                foreach ($goods_idarr as $key=>$val){
                    $gaction_data=array(
                        'goods_id'=>$val,
                        'action_user'=>'系统脚本',
                        'action_time'=>gmtime(),
                        'action_type'=>'商品还原',
                        'old_value'=>'',
                        'new_value'=>''
                    );
                    $goods_action_mod->add($gaction_data);
                }
            }
        }
    }
   
   /*
    * 
    * 每天定时凌晨2点生成全仓商品数据，并且导入生成excel表格入库  - 不使用已放弃
    * */
    public function auto_export_allgoods_bak(){
        set_time_limit(0);
        import('Org.Util.PHPExcel');
        //import('Org.Util.PHPExcel.CachedObjectStorageFactory');
        //import('Org.Util.PHPExcel.Settings');
        $goodsdata=M('goods')->alias('g')
                  ->field('g.goods_id,g.goods_name,g.goods_sn,c.cat_name,g.origin,g.goods_weight,g.spec_value,g.spec_unit,mp.user_price as vip_price,mp2.user_price as reg_price,g.promote_price,g.sources,g.is_on_sale,g.is_offline,g.is_presell')
                  ->join(C ( 'DB_PREFIX' ).'category as c on g.cat_id=c.cat_id')
                  ->join(C ( 'DB_PREFIX' ).'member_price as mp ON g.goods_id=mp.goods_id AND mp.user_rank=2')
                  ->join(C ( 'DB_PREFIX' ).'member_price as mp2 ON g.goods_id=mp2.goods_id AND mp2.user_rank=1')
                  ->select();
        if($goodsdata){
            /*$cacheMethod=new \PHPExcel_CachedObjectStorageFactory();
            $cachephptemp=$cacheMethod->cache_to_phpTemp;
            $cacheSettings = array('memoryCacheSize'=>'64MB');
            $objSettings=new \PHPExcel_Settings();
            $objSettings->setCacheStorageMethod($cachephptemp,$cacheSettings);*/
            $objPhpExcel=new \PHPExcel();
            $objPhpExcel->getActiveSheet()->getDefaultColumnDimension()->setAutoSize(true);
            $f_head_arr = array(
                "编号", "商品名称", "货号", "分类","产地","商品重量","商品属性","全仓库存","花城汇仓","注册价(元)","VIP价(元)","促销价(元)","进价(元)","是否891","上架","线下","销售方式","供应商名称","供应商联系方式"
            );
            foreach ( $f_head_arr as $fkey=>$fval ){
                $objPhpExcel->getActiveSheet()->getStyleByColumnAndRow($fkey, 1)->getFont()->setBold(true);
                $objPhpExcel->getActiveSheet()
                ->getStyleByColumnAndRow($fkey, 1)
                ->getAlignment()
                ->setHorizontal('center');
                $objPhpExcel->getActiveSheet()->setCellValueByColumnAndRow($fkey, 1, $fval);
            }
           
            $objPhpExcel->setActiveSheetIndex(0);
            $objActSheet = $objPhpExcel->getActiveSheet();
            $time=time();
            $y=date('Y',$time);
            $m=date('m',$time);
            $d=date('d',$time);
            $his=date('His',$time);
            $title=$y.'-'.$m.'-'.$d.'-'.$his;
            $objActSheet->setTitle('全仓商品数据汇总-'.$title);
            $row_num = 0;
            $i = 0;
            $goods_storage_mod=M('goods_storage');
            foreach ($goodsdata as $k=>$v){
                $row_num = $i + 2;
                if($v['goods_weight']>0){
                    $goods_weight=$this->get_goods_weight($v['goods_weight']);
                }else{
                    $goods_weight='';
                }
                $practical_num_sum=$goods_storage_mod->where(array('goods_id'=>$v['goods_id'],'wid'=>array('in',array(1,8))))->sum('practical_num');
                $practical_num_sum8=$goods_storage_mod->where(array('goods_id'=>$v['goods_id'],'wid'=>8))->sum('practical_num');
                if($v['sources']=='891'){
                    $sources='是';
                }else{
                    $sources='否';
                }
                if($v['is_on_sale']==1){
                    $is_on_sale='是';
                }else{
                    $is_on_sale='否';
                }
                if($v['is_offline']==1){
                    $is_offline='是';
                }else{
                    $is_offline='否';
                }
                if($v['is_presell']==0){
                    $is_presell='现售';
                }elseif($v['is_presell']==1){
                    $is_presell='预售';
                }
                if($practical_num_sum==''){
                    $practical_num_sum=0;
                }
                if($practical_num_sum8==''){
                    $practical_num_sum8=0;
                }
                $objPhpExcel->setActiveSheetIndex(0)
                ->setCellValue('A'.$row_num, $v['goods_id'])
                ->setCellValue('B'.$row_num, $v['goods_name'])
                ->setCellValue('C'.$row_num, "'".$v['goods_sn'])
                ->setCellValue('D'.$row_num, $v['cat_name'])
                ->setCellValue('E'.$row_num, $v['origin'])
                ->setCellValue('F'.$row_num, $goods_weight)
                ->setCellValue('G'.$row_num, $v['spec_value'].'/'.$v['spec_unit'])
                ->setCellValue('H'.$row_num, $practical_num_sum)
                ->setCellValue('I'.$row_num, $practical_num_sum8)
                ->setCellValue('J'.$row_num, $v['reg_price'])
                ->setCellValue('K'.$row_num, $v['vip_price'])
                ->setCellValue('L'.$row_num, $v['promote_price'])
                ->setCellValue('M'.$row_num, $sources)
                ->setCellValue('N'.$row_num, $is_on_sale)
                ->setCellValue('O'.$row_num, $is_offline)
                ->setCellValue('P'.$row_num, $is_presell);
                $i++;
            }
            
            unset( $f_head_arr );
            unset( $goodsdata );
            ob_end_clean();
            //-/ 请求头部设置
            $file_name = 'All-Goods-'.$title;
            /*header("Content-Type: application/force-download");
            header("Content-Transfer-Encoding: utf-8");
            header("Pragma: no-cache");
            header('Content-Disposition: attachement;filename="'.$file_name.'.xls"');
            header("Cache-Control: max-age=0");*/
            $dirname=date('Y-m-d');
            $targetFolder='/Public/allgoodsxls/'.$dirname.'/';
            if (!file_exists($_SERVER['DOCUMENT_ROOT'].'/Public')||!is_dir($_SERVER['DOCUMENT_ROOT'].'/Public')){
                mkdir($_SERVER['DOCUMENT_ROOT'].'/Public',0777,true);
            }
            $firstLetterDir=$_SERVER['DOCUMENT_ROOT'].'/Public/allgoodsxls/';
            if (!file_exists($firstLetterDir)||!is_dir($firstLetterDir)){
                mkdir($firstLetterDir,0777,true);
            }
            if (!file_exists($firstLetterDir.'/'.$dirname)||!is_dir($firstLetterDir.'/'.$dirname)){
                mkdir($firstLetterDir.'/'.$dirname,0777,true);
            }
            $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
            $filename=$file_name.'.xls';
            $targetFile = rtrim($targetPath,'/') . '/' .$filename ;
            import('Org.Util.PHPExcel.IOFactory');
            $objWriter = \PHPExcel_IOFactory::createWriter($objPhpExcel, 'Excel5');
            echo $targetFile;
            $objWriter->save($targetFile);
        }
    }
    
    public function auto_export_allgoods(){
        set_time_limit(0);
        $goodsdata=M('goods')->alias('g')
        ->field('g.goods_id,g.goods_name,g.goods_sn,g.cat_id,g.brand_id,g.origin,g.goods_weight,g.spec_value,g.spec_unit,mp.user_price as vip_price,mp2.user_price as reg_price,g.promote_price,g.sources,g.is_on_sale,g.is_offline,g.is_presell,g.is_delete')
        //->join(C ( 'DB_PREFIX' ).'category as c on g.cat_id=c.cat_id')
        ->join(C ( 'DB_PREFIX' ).'member_price as mp ON g.goods_id=mp.goods_id AND mp.user_rank=2')
        ->join(C ( 'DB_PREFIX' ).'member_price as mp2 ON g.goods_id=mp2.goods_id AND mp2.user_rank=1')
        ->where(array('g.goods_name'=>array('neq','')))
        ->select();
        if($goodsdata){
            
            $f_head_arr = array(
                "编号", "商品名称", "货号", "分类","品牌","产地","商品重量","商品属性","注册价(元)","VIP价(元)","促销价(元)","是否891","线下","销售方式","是否删除","删除时间","总仓库存"
            );
            //-/ 请求头部设置
            $title=date('Y-m-d',time()).'-'.date('His',time());
            $file_name = 'All-Goods-'.$title;
            $dirname=date('Y-m-d');
            $targetFolder='/Public/allgoodsxls/'.$dirname.'/';
            if (!file_exists($_SERVER['DOCUMENT_ROOT'].'/Public')||!is_dir($_SERVER['DOCUMENT_ROOT'].'/Public')){
                mkdir($_SERVER['DOCUMENT_ROOT'].'/Public',0777,true);
            }
            $firstLetterDir=$_SERVER['DOCUMENT_ROOT'].'/Public/allgoodsxls/';
            if (!file_exists($firstLetterDir)||!is_dir($firstLetterDir)){
                mkdir($firstLetterDir,0777,true);
            }
            if (!file_exists($firstLetterDir.'/'.$dirname)||!is_dir($firstLetterDir.'/'.$dirname)){
                mkdir($firstLetterDir.'/'.$dirname,0777,true);
            }
            $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
            $filename=$file_name.'.csv';
            $targetFile = rtrim($targetPath,'/') . '/' .$filename ;
            $file=fopen($targetFile, "wb");
            if(is_file($file)){
                returnApiError('fopen error!');
            }
            $widwhere=array('in','8,17,18');
            //$wwhere=array('status'=>1,'pid'=>0);
            $wwhere=array('status'=>1,'pid'=>0,'id'=>$widwhere);
            $wdata=M('warehouse')->field('id,name')->where($wwhere)->select();
            if($wdata){
                foreach ($wdata as $k=>$v){
                    $f_head_arr[]=$v['name'].'库存';
                    $f_head_arr[]='上架('.$v['name'].')';
                    $f_head_arr[]='进价('.$v['name'].')';
                    $f_head_arr[]='是否在架('.$v['name'].')';
                    $f_head_arr[]='是否有采购记录('.$v['name'].')';
                    $f_head_arr[]='供应商名称('.$v['name'].')';
                    $f_head_arr[]='供应商联系人('.$v['name'].')';
                    $f_head_arr[]='供应商联系方式('.$v['name'].')';
                }
            }
            foreach ( $f_head_arr as $fkey=>$fval ){
                $f_head_arr[$fkey] = iconv('utf-8', 'gbk', $fval);
            }
            fputcsv($file, $f_head_arr); 
            // 计数器
            $cnt = 0;
            // 每隔$limit行，刷新一下输出buffer，不要太大，也不要太小
            $limit = 100000;
            $goods_storage_mod=M('goods_storage');
            $goods_action_mod=M('goods_action');
            $shelves_goods_mod=M('shelves_goods');
            $warehouse_procurement_mod=M('warehouse_procurement');
            $warehouse_procurement_detail_mod=M('warehouse_procurement_detail');
            $category_mod=M('category');
            $brand_mod=M('brand');
            //$goods8_mod=M('goods_wid_8');
            foreach ($goodsdata as $k=>$v){
                $temp_arr=array();
                $cnt ++;
                if($limit == $cnt){
                    //刷新一下输出buffer，防止由于数据过多造成问题
                    ob_flush();
                    flush();
                    $cnt = 0;
                }
                if($v['goods_weight']>0){
                    $goods_weight=$this->get_goods_weight($v['goods_weight']);
                }else{
                    $goods_weight='';
                }
                $cat_name=$category_mod->where(array('cat_id'=>$v['cat_id']))->getField('cat_name');
                $brand_name=$brand_mod->where(array('brand_id'=>$v['brand_id']))->getField('brand_name');
                $practical_num_sum=$goods_storage_mod->where(array('goods_id'=>$v['goods_id'],'wid'=>$widwhere))->sum('practical_num');
                //$practical_num_sum=$goods_storage_mod->where(array('goods_id'=>$v['goods_id']))->sum('practical_num');

                if(empty($cat_name)){
                    $cat_name='';
                }
                if($v['sources']=='891'){
                    $sources='是';
                }else{
                    $sources='否';
                }
                if($v['is_offline']==1){
                    $is_offline='是';
                }else{
                    $is_offline='否';
                }
                if($v['is_presell']==0){
                    $is_presell='现售';
                }elseif($v['is_presell']==1){
                    $is_presell='预售';
                }
                if($practical_num_sum==''){
                    $practical_num_sum=0;
                }
                $goods_action_data='';
                if($v['is_delete']==0){
                    $is_delete='否';
                }elseif ($v['is_delete']==1){
                    $is_delete='是';
                    $goods_action_data=$goods_action_mod->where(array('goods_id'=>$v['goods_id'],'action_type'=>'商品删除'))->order('id desc')->find();
                }
                
                if($goods_action_data){
                    $delete_time=local_date('Y-m-d H:i:s',$goods_action_data['action_time']);
                }else{
                    $delete_time='';
                }
                $temp_arr['goods_id'] = iconv('utf-8', 'gbk', $v['goods_id']);
                $temp_arr['goods_name'] = iconv('utf-8', 'gbk',$v['goods_name']);
                $temp_arr['goods_sn'] = iconv('utf-8', 'gbk',"'".$v['goods_sn']);
                $temp_arr['cat_name'] = iconv('utf-8', 'gbk',$cat_name);
                $temp_arr['brand_name'] = iconv('utf-8', 'gbk',$brand_name);
                $temp_arr['origin'] = iconv('utf-8', 'gbk',$v['origin']);
                $temp_arr['goods_weight'] = iconv('utf-8', 'gbk',$goods_weight);
                $temp_arr['spec_str'] = iconv('utf-8', 'gbk',$v['spec_value'].'/'.$v['spec_unit']);
                $temp_arr['reg_price'] = iconv('utf-8', 'gbk',$v['reg_price']);
                $temp_arr['vip_price'] = iconv('utf-8', 'gbk',$v['vip_price']);
                $temp_arr['promote_price'] = iconv('utf-8', 'gbk',$v['promote_price']);
                $temp_arr['sources'] = iconv('utf-8', 'gbk',$sources);
                $temp_arr['is_offline'] = iconv('utf-8', 'gbk',$is_offline);
                $temp_arr['is_presell'] = iconv('utf-8', 'gbk',$is_presell);
                $temp_arr['is_delete'] = iconv('utf-8', 'gbk',$is_delete);
                $temp_arr['delete_time'] = iconv('utf-8', 'gbk',$delete_time);
                $temp_arr['practical_num_sum'] = iconv('utf-8', 'gbk',$practical_num_sum);
                if($wdata){
                    foreach ($wdata as $key=>$val){
                        $goods_xx_mod=M('goods_wid_'.$val['id']);
                        $practical_num_sum_xx=$goods_storage_mod->where(array('goods_id'=>$v['goods_id'],'wid'=>$val['id']))->sum('practical_num');
                        $is_on_sale_xx=$goods_xx_mod->where(array('goods_id'=>$v['goods_id']))->getField('is_on_sale');
                        if($is_on_sale_xx==''){
                            if($v['is_on_sale']==1){
                                $is_on_sale='是';
                            }else{
                                $is_on_sale='否';
                            }
                        }else{
                            if($is_on_sale_xx==1){
                                $is_on_sale='是';
                            }else{
                                $is_on_sale='否';
                            }
                        }
                        
                        $is_shelves=$shelves_goods_mod->alias('sg')
                        ->join(C ( 'DB_PREFIX' ).'shelves as s on s.id=sg.sh_id')
                        ->where(array('goods_sn'=>$v['goods_sn'],'s.wid'=>$val['id']))
                        ->count();
                        if($is_shelves){
                            $is_shelves='是';
                        }else{
                            $is_shelves='否';
                        }
                        
                        $wpddata=$warehouse_procurement_detail_mod->field('procurement_price,procurement_id')
                        ->where(array('wid'=>$val['id'],'status'=>array('NEQ',3),'goods_id'=>$v['goods_id']))
                        ->order('id DESC')
                        ->find();
                        $procurement_price=0.00;
                        $is_warehouse_procurement='否';
                        $wsname='';
                        $wsphone='';
                        $contact_info='';
                        if($wpddata){
                            $wplist=$warehouse_procurement_mod->alias('wp')
                            ->field('ws.name,ws.phone,ws.contact_info')
                            ->join(C ( 'DB_PREFIX' ).'warehouse_supplier as ws on wp.supplier_id=ws.id')
                            ->where(array('wp.id'=>$wpddata['procurement_id']))
                            ->find();
                            if($wplist){
                                $procurement_price=$wpddata['procurement_price'];
                                if($wpddata['procurement_price']==''){
                                    $procurement_price=0.00;
                                }
                                $is_warehouse_procurement='是';
                                $wsname=$wplist['name'];
                                $wsphone=$wplist['phone'];
                                $contact_info=$wplist['contact_info'];
                            }
                        }
                        if($practical_num_sum_xx==''){
                            $practical_num_sum_xx=0;
                        }
                        $temp_arr['practical_num_sum_'.$val['id']] = iconv('utf-8', 'gbk',$practical_num_sum_xx);
                        $temp_arr['is_on_sale_'.$val['id']] = iconv('utf-8', 'gbk',$is_on_sale);
                        $temp_arr['procurement_price_'.$val['id']] = iconv('utf-8', 'gbk',$procurement_price);
                        $temp_arr['is_shelves_'.$val['id']] = iconv('utf-8', 'gbk',$is_shelves);
                        $temp_arr['is_warehouse_procurement_'.$val['id']] = iconv('utf-8', 'gbk',$is_warehouse_procurement);
                        $temp_arr['wsname_'.$val['id']] = iconv('utf-8', 'gbk',$wsname);
                        $temp_arr['wsphone_'.$val['id']] = iconv('utf-8', 'gbk',"'".$wsphone);
                        $temp_arr['contact_info_'.$val['id']] = iconv('utf-8', 'gbk',"'".$contact_info);
                    }
                } 
                fputcsv($file, $temp_arr);
                unset($temp_arr);
            }
            unset($goodsdata);
            ob_flush();
            flush();
        }
    }
    
    private function get_goods_weight($val){
        if($val>0){
            if($val>=1){
                return $val.'/kg';
            }else{
                return ($val/ 0.001).'/g';
            }
        }
        return $val;
    
    }
    
    /*
     * 下载指定文件
     * */
    public function down_allgoods(){
        set_time_limit(0);
        $filename=I('request.date');
        
        if(empty($filename)){
            $filename=date('Y-m-d',time());
        }
        $filename=strtotime($filename);
        if($filename===false){
            returnApiError('输入下载对应时间不对');
        }else{
            $filename=date('Y-m-d',$filename);
        }
        $targetFolder='/Public/allgoodsxls/'.$filename.'/';
        $firstLetterDir=$_SERVER['DOCUMENT_ROOT'].'/Public/allgoodsxls/'.$filename.'/';
        if (!file_exists($firstLetterDir)||!is_dir($firstLetterDir)){
            returnApiError('输入下载对应时间文件目录不存在');
        }
        $files=$this->folder_list($firstLetterDir, 'csv');
        if(count($files)>0){
            $this->download_file($files[0]);
        }else{
            returnApiError('无下载数据');
        }
    }
    
    private function download_file($file){
        if(is_file($file)){
            $length = filesize($file);
            //$type = mime_content_type($file);
            $type='application/vnd.ms-excel';
            $showname =  ltrim(strrchr($file,'/'),'/');
            header("Content-Description: File Transfer");
            header('Content-type: ' . $type);
            header('Content-Length:' . $length);
             if (preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT'])) { //for IE
                 header('Content-Disposition: attachment; filename="' . rawurlencode($showname) . '"');
             } else {
                 header('Content-Disposition: attachment; filename="' . $showname . '"');
             }
             readfile($file);
             exit;
         } else {
             exit('文件已被删除！');
         }
     }
    
    /*
     *搜索扩展指定文件扩展 
     * */
    private function get_files_by_ext($path, $ext){
        $files = $file= array();
        if (is_dir($path)){
            $handle = opendir($path);
            $file = readdir($handle);
            while ($file!==false) {
                if ($file[0] == '.'){ continue; }
                if (is_file($path.$file) and preg_match('/\.'.$ext.'$/', $file)){
                    $files[] = $file;
                }
            }
            closedir($handle);
            sort($files);
        }
      
        return $files;
  
   }
   
   /**
    *
    * 遍历文件夹目录
    * @param $dir 遍历路径
    * @author jourmy@hotmail.com
    */
   private function folder_list($dir,$ext){
       $dir .= substr($dir, -1) == '/' ? '' : '/';
       $dirInfo = array();
       foreach (glob($dir.'*'.$ext) as $v) {
           $dirInfo[] = $v;
           if(is_dir($v)){
               $dirInfo = array_merge($dirInfo, $this->folder_list($v));
           }
       }
       sort($dirInfo);
       return $dirInfo;
   }
    
    /*
     * 同步次品数据
     * */
    public function check_cipin(){
        $wid=I('request.wid','intval');
        $count=0;
        if($wid){
            $bdlist=M('backflow_defectivegoods')->where(array('wid'=>$wid))->select();
            if($bdlist){
                $gs_mod=M('goods_storage');
                foreach ($bdlist as $k=>$v){
                    $gslist=$gs_mod->where(array('wid'=>$v['wid'],'goods_id'=>$v['goods_id']))->find();
                    if($gslist['id']>0 && $gslist['id']!=$v['goods_storage_id']){
                        $bdid=M('backflow_defectivegoods')->where(array('id'=>$v['id']))->save(array('goods_storage_id'=>$gslist['id']));
                        if($bdid!==false){
                            echo 'bdid=>'.$v['id'].'=>wid=>'.$v['wid'].'=>goods_id=>'.$v['goods_id'].'<br />';
                            $count=$count+1;
                        }
                    }else{
                        continue;
                    }
                }
                echo $count;
            }else{
                echo 'no data';
                exit;
            }
        }else{
            echo 'error';
            exit;
        }
    }
    
    public function check(){
        $this->system_service_source_no();//检查库存系统工作平台数据
    }
    
    /*
     * 定时清空冻结预警日志表
     * */
    public function del_system_service_log(){
        $sql='delete from sdx_system_service_log';
        M()->execute($sql);
        
    }
     /*
     * 插入系统工作日志
     * */
    private function system_service_log($wid,$source_no,$type){
        $data_arr=array(
            'wid'=>$wid,
            'source_no'=>$source_no,
            'log_type'=>$type,
            'status'=>0
        );
        M('system_service_log')->add($data_arr);
    }
    
   /*
    * 检查系统工作日志是否已经存在
    */
    private function check_repeat_system_service_log($wid,$source_no,$type){
        $id=M('system_service_log')->where(array('wid'=>$wid,'source_no'=>$source_no,'log_type'=>$type))->getField('id');
        if($id>0){
            return false;
        }else{
            return true;
        }
    }
    
    /*
     * 冻存预警
     * */
     private function system_service_source_no(){
        ini_set('max_execution_time', '0');
        set_time_limit(0);
        //ini_set('memory_limit','4096M');
        $page=S('system_service_source_no_page');
        if(empty($page)||!is_numeric($page)){
            S('system_service_source_no_page',1,86400);
            $page=1;
        }
        $begin_num = ($page-1)*$this->pagesize;
        $goods_freeze_record_mod=M('goods_freeze_record');
        $system_service_log_mod=M('system_service_log');
        $system_service_log_mod->where(array('status'=>1,'log_type'=>1))->delete();
        $sql_count="SELECT COUNT(DISTINCT source_no) as s_count FROM sdx_goods_freeze_record WHERE wid = 8 AND is_check=0 AND record_type <> 13";
        /*$sql_count='SELECT COUNT(source_no) as s_count FROM('.
            'SELECT wid,source_no FROM sdx_goods_freeze_record WHERE wid=8 and record_type<>13 GROUP BY source_no) as tt';*/
        $s_count=M()->query($sql_count);
        $count=$s_count[0]['s_count'];
        $all_page = ceil($count/$this->pagesize);
        $gfrlist=$goods_freeze_record_mod->field('wid,source_no')->where(array('wid'=>8,'is_check'=>0,'record_type'=>array('neq',13)))->group('source_no')->limit($begin_num.",".$this->pagesize)->select();
        if($gfrlist){
            $order_info_mod=M('order_info');
            $source_no_group=array();//来源单号分组
            foreach ($gfrlist as $key=>$val){
                if(!empty($val['source_no'])){
                    $source_no_2=substr($val['source_no'],0,2);
                    if(is_numeric($source_no_2)){
                        $oires=$order_info_mod->field('order_id,order_sn,batch_no,wid')->where(array('wid'=>$val['wid'],'order_sn'=>$val['source_no']))->select();
                        if($oires){
                            foreach ($oires as $k=>$v){
                                $v['source_no']=$v['order_sn'];
                                if($v['batch_no']==0){
                                    $source_no_group[$v['order_sn']][]=$v;
                                }else{
                                    $source_no_group[$v['batch_no']][]=$v;
                                }
                            }
                        }else{
                            $source_no_group[$val['source_no']][]=$val;
                        }
                    }else{
                        $source_no_group[$val['source_no']][]=$val;
                    }
              }
              unset($gfrlist[$key]);
            }
            $plus_status=array(2,4,7);
            $subtraction_status=array(1,3,5,6,8,9,10,11,12,15,14,16);
            dump($source_no_group);
            foreach ($source_no_group as $key=>$val){
                if(count($val)>1){
                    $wid=$val[0]['wid'];
                    $source_no_str=array();
                    $plus=0;
                    $subtraction=0;
                    $plus_freeze_num=0;
                    $subtraction_freeze_num=0;
                    foreach ($val as $k=>$v){
                        $source_no_str[]=$v['source_no'];
                    }
                    $source_no=implode(',',$source_no_str);
                    $gfr_s=$goods_freeze_record_mod->field('wid,source_no,freeze_num,record_type')->where(array('source_no'=>array('in',$source_no),'wid'=>$wid))->select();
                    if($gfr_s){
                        foreach ($gfr_s as $kk=>$vv){
                            if($vv['wid']!=0){
                                if(in_array($vv['record_type'], $plus_status)){
                                    $plus++;
                                    $plus_freeze_num+=$vv['freeze_num'];
                                    unset($gfr_s[$kk]);
                                }
                                if(in_array($vv['record_type'], $subtraction_status)){
                                    $subtraction++;
                                    $subtraction_freeze_num+=$vv['freeze_num'];
                                    unset($gfr_s[$kk]);
                                }
                            }
                        }
                    }
                    dump($source_no_str);
                    echo $plus.'=>'.$subtraction.'<br />';
                    echo 'plus_freeze_num=>'.$plus_freeze_num.'=subtraction_freeze_num=>'.$subtraction_freeze_num.'<br />';
                    if($plus!==$subtraction){
                        if($plus_freeze_num!==$subtraction_freeze_num){
                            foreach ($source_no_str as $kkk=>$vvv){
                                $goods_freeze_record_mod->where(array('wid'=>$wid,'source_no'=>$vvv))->save(array('is_check'=>0));
                                if($this->check_repeat_system_service_log($wid,$vvv,1)){
                                    $this->system_service_log($wid,$vvv,1);
                                }else{
                                    continue;
                                }
                            }
                        }else{
                            $goods_freeze_record_mod->where(array('wid'=>$wid,'source_no'=>array('in',$source_no)))->save(array('is_check'=>1));
                        }
                        unset($source_no_group[$key]);
                        continue;
                    }else{
                        foreach ($source_no_str as $kkk=>$vvv){
                            $goods_freeze_record_mod->where(array('wid'=>$wid,'source_no'=>$vvv))->save(array('is_check'=>1));
                            if($this->check_repeat_system_service_log($wid,$vvv,1)){
                                $system_service_log_mod->where(array('wid'=>$wid,'source_no'=>$vvv,'log_type'=>1))->save(array('status'=>1));
                            }else{
                                continue;
                            }
                        }
                        unset($source_no_group[$key]);
                        continue;
                    }
                }else{
                    $wid=$val[0]['wid'];
                    $source_no=$val[0]['source_no'];
                    $plus=0;
                    $subtraction=0;
                    $plus_freeze_num=0;
                    $subtraction_freeze_num=0;
                    $gfr_s=$goods_freeze_record_mod->field('wid,source_no,freeze_num,record_type')->where(array('source_no'=>$source_no,'wid'=>$wid))->select();
                    if($gfr_s){
                        foreach ($gfr_s as $kk=>$vv){
                            if($vv['wid']!=0){
                                if(in_array($vv['record_type'], $plus_status)){
                                    $plus++;
                                    $plus_freeze_num+=$vv['freeze_num'];
                                    unset($gfr_s[$kk]);
                                }
                                if(in_array($vv['record_type'], $subtraction_status)){
                                    $subtraction++;
                                    $subtraction_freeze_num+=$vv['freeze_num'];
                                    unset($gfr_s[$kk]);
                                }
                            }
                        }
                    }
                    echo $source_no.'=>'.$plus.'=>'.$subtraction.'<br />';
                    echo 'plus_freeze_num=>'.$plus_freeze_num.'=subtraction_freeze_num=>'.$subtraction_freeze_num.'<br />';
                    if($plus!==$subtraction){
                        if($plus_freeze_num!==$subtraction_freeze_num){
                               $goods_freeze_record_mod->where(array('wid'=>$wid,'source_no'=>$source_no))->save(array('is_check'=>0));
                               if($this->check_repeat_system_service_log($wid,$source_no,1)){
                                    $this->system_service_log($wid,$source_no,1);
                                }else{
                                    continue;
                                }
                        }else{
                            $goods_freeze_record_mod->where(array('wid'=>$wid,'source_no'=>$source_no))->save(array('is_check'=>1));
                        }
                        unset($source_no_group[$key]);
                         continue;
                        
                    }else{
                        $goods_freeze_record_mod->where(array('wid'=>$wid,'source_no'=>$source_no))->save(array('is_check'=>1));
                        if($this->check_repeat_system_service_log($wid,$source_no,1)){
                                $system_service_log_mod->where(array('wid'=>$wid,'source_no'=>$source_no,'log_type'=>1))->delete();
                        }else{
                                continue;
                        }
                        unset($source_no_group[$key]);
                        continue;
                    }
                }
                
            }
    }
    $next_page = $page+1;
    S('system_service_source_no_page',$next_page,86400);
    if($next_page>$all_page){
        S('system_service_source_no_page',1,86400);
    }
  }
    /*
     * 冻存预警
     * */
    private function system_service_source_no_bak(){
        ini_set('max_execution_time', '0');
        set_time_limit(0);
        //ini_set('memory_limit','4096M');
        $page=S('system_service_source_no_page');
        if(empty($page)||!is_numeric($page)){
            S('system_service_source_no_page',1,86400);
            $page=1;
        }
        $begin_num = ($page-1)*$this->pagesize;
        $goods_freeze_record_mod=M('goods_freeze_record');
        $goods_freeze_record_mod->where(array('status'=>1,'log_type'=>1))->delete();
        $sql_count="SELECT COUNT(DISTINCT source_no) as s_count FROM sdx_goods_freeze_record WHERE wid = 8 AND record_type <> 13";
        /*$sql_count='SELECT COUNT(source_no) as s_count FROM('.
                   'SELECT wid,source_no FROM sdx_goods_freeze_record WHERE wid=8 and record_type<>13 GROUP BY source_no) as tt';*/
        $s_count=M()->query($sql_count);
        $count=$s_count[0]['s_count'];
        $all_page = ceil($count/$this->pagesize);
        $gfrlist=$goods_freeze_record_mod->field('wid,source_no')->where(array('wid'=>8,'record_type'=>array('neq',13)))->group('source_no')->limit($begin_num.",".$this->pagesize)->select();
        if($gfrlist){
            $plus_status=array(2,4,7);
            $subtraction_status=array(1,3,5,6,8,9,10,11,12,15,14,16);
            foreach ($gfrlist as $key=>$val){
                if(!empty($val['source_no'])){
                    $gfr_s=$goods_freeze_record_mod->field('wid,source_no,record_type')->where(array('source_no'=>$val['source_no'],'wid'=>$val['wid']))->select();
                    if($gfr_s){
                            $plus=0;
                            $subtraction=0;
                            foreach ($gfr_s as $k=>$v){
                                if($v['wid']!=0){
                                    if(in_array($v['record_type'], $plus_status)){
                                            $plus++;
                                            unset($gfr_s[$k]);
                                    }
                                    if(in_array($v['record_type'], $subtraction_status)){
                                        $subtraction++;
                                        unset($gfr_s[$k]);
                                    }
                               }
                        }
                    }
                    echo $val['source_no'].'=>'.$plus.'=>'.$subtraction.'<br />';
                    if($plus!==$subtraction){
                        if($this->check_repeat_system_service_log($val['wid'],$val['source_no'],1)){
                            $this->system_service_log($val['wid'],$val['source_no'],1);
                        }else{
                            continue;
                        }
                    }else{
                        if($this->check_repeat_system_service_log($val['wid'],$val['source_no'],1)){
                            $goods_freeze_record_mod->where(array('wid'=>$val['wid'],'source_no'=>$val['source_no'],'log_type'=>$val['log_type']))->delete();
                        }else{
                            continue;
                        }
                    }
                }
                unset($gfrlist[$key]);
            }
        }
        $next_page = $page+1;
        S('system_service_source_no_page',$next_page,86400);
        if($next_page>$all_page){
            S('system_service_source_no_page',1,86400);
        }
    }
    
    /*
     * 批量读取Excel
     * */
    public  function updatagoodsprice(){
        header("Content-type: text/html; charset=utf-8");
        set_time_limit(0);
        import('Org.Util.PHPExcel');
        import("Org.Util.PHPExcel.Reader.Excel5");
        //import('Org.Util.PHPExcel.IOFactory');
        $targetFolder='/Public/';
        if (!file_exists($_SERVER['DOCUMENT_ROOT'].'/Public')||!is_dir($_SERVER['DOCUMENT_ROOT'].'/Public')){
            mkdir($_SERVER['DOCUMENT_ROOT'].'/Public',0777,true);
        }
        $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
        $filename='update_goods_price.xls';
        $targetFile = rtrim($targetPath,'/') . '/' .$filename ;
        $PHPReader = new \PHPExcel_Reader_Excel5();  
        if (!file_exists($targetFile)) {
            die('no file!');
        }
    //载入文件
            $PHPExcel = $PHPReader->load($targetFile);
        //获取表中的第一个工作表，如果要获取第二个，把0改为1，依次类推
            $currentSheet=$PHPExcel->getActiveSheet();
           // $currentSheet = $PHPExcel->getSheet(0);
        //    $allColumn = $currentSheet->getHighestColumn();  //获取总列数
            $allRow = $currentSheet->getHighestRow();  //获取总行数
           
        //导入PHPExcel.Shared.Date 用以处理时间类型
           
        //循环获取表中的数据,
            $goods_mod=M('goods');
            $goods_action_mod=M('goods_action');
            $member_price_mod=M('member_price');
            $goods_price_tag_service = new GoodsPriceTagService();
            for ($Row = 2; $Row <= $allRow; $Row++) {
                echo $Row."=>";
                $goods_sn=$currentSheet->getCell('A' . $Row)->getValue();
                $shop_price=floatval($currentSheet->getCell('B' . $Row)->getValue());
                $vip_price=floatval($currentSheet->getCell('C' . $Row)->getValue());
                $goods_data=$this->check_goods_exists($goods_sn);
                if(!$goods_data){
                    echo 'ERROR=>货号：'.$goods_sn.'=>售价：'.$shop_price."=>VIP：".$vip_price.'<br />';
                    continue;
                }
                if($goods_mod->where(array('goods_id'=>$goods_data['goods_id']))->save(array('shop_price'=>$shop_price))!==false){
                    $action_data=array(
                        'goods_id'=>$goods_data['goods_id'],
                        'action_user'=>'系统自动处理',
                        'action_time'=>gmtime(),
                        'action_type'=>'本店售价',
                        'old_value'=>$goods_data['shop_price'],
                        'new_value'=>$shop_price,
                    );
                    $goods_action_mod->add($action_data);
                    unset($action_data);
                    if($member_price_mod->where(array('goods_id'=>$goods_data['goods_id'],'user_rank'=>1))->save(array('user_price'=>$shop_price))!==false){
                        $maction_data=array(
                            'goods_id'=>$goods_data['goods_id'],
                            'action_user'=>'系统自动处理',
                            'action_time'=>gmtime(),
                            'action_type'=>'注册用户',
                            'old_value'=>$goods_data['reg_price'],
                            'new_value'=>$shop_price,
                        );
                        $goods_action_mod->add($maction_data);
                        unset($maction_data);
                    }
                    if($member_price_mod->where(array('goods_id'=>$goods_data['goods_id'],'user_rank'=>2))->save(array('user_price'=>$vip_price))!==false){
                        $maction_data=array(
                            'goods_id'=>$goods_data['goods_id'],
                            'action_user'=>'系统自动处理',
                            'action_time'=>gmtime(),
                            'action_type'=>'VIP用户',
                            'old_value'=>$goods_data['vip_price'],
                            'new_value'=>$vip_price,
                        );
                        $goods_action_mod->add($maction_data);
                        unset($maction_data);
                    }

                    /**
                     * 推送到电子价格牌系统
                     * Created By Min
                     */
                    $goods_price_tag_service->improtGoods($goods_data['goods_id']);

                    echo 'ID:'.$goods_data['goods_id'].'=>货号：'.$goods_sn.'=>售价：'.$shop_price."=>VIP：".$vip_price.'<br />';
                    unset($goods_sn);
                    unset($shop_price);
                    unset($vip_price);
                    unset($goods_data);
                }else{
                    echo 'ERROR=>货号：'.$goods_sn.'=>售价：'.$shop_price."=>VIP：".$vip_price.'<br />';
                    continue;
                }
            }
            $option = array(
                'del_keys'  =>  true,
            );
            S('user_price_', '', $option);
            S('godds_final_price_', '', $option);
           
    }
    
    /*
     * 根据商品货号检查商品是否存在，若存在返回商品数据。否则返回false
     * */
    private function check_goods_exists($goods_sn=''){
        if(empty($goods_sn)){
            return false;
        }
        $goods_data=M('goods')->alias('g')
                 ->field('g.goods_id,g.shop_price,mp.user_price as reg_price,mp1.user_price as vip_price')
                 ->join(C ( 'DB_PREFIX' ).'member_price as mp on mp.goods_id=g.goods_id and mp.user_rank=1')
                 ->join(C ( 'DB_PREFIX' ).'member_price as mp1 on mp1.goods_id=g.goods_id and mp1.user_rank=2')
                 ->where(array('g.goods_sn'=>$goods_sn))
                 ->find();
        if($goods_data){
          return $goods_data;  
        }else{
            return false;
        }
    }

    /**
    *   根据商品货号以及对应仓库ID检查该仓库是否存在该商品，若存在返回商品数据。否则返回false
     */
    private function check_goods_storage_exists($goods_sn='',$wid=0){
        if(empty($goods_sn) || empty($wid)){
            return false;
        }
        $goods_storage_data=M('goods_storage')->alias('gs')
                            ->field('g.goods_id,g.goods_sn,g.goods_name,gs.id as goods_storage_id,gs.wid,gs.practical_num,gs.freeze_num')
                            ->join(C ( 'DB_PREFIX' ).'goods as g on g.goods_id=gs.goods_id')
                            ->where(array('g.goods_sn'=>$goods_sn,'gs.wid'=>$wid))
                            ->find();
        if($goods_storage_data){
            return $goods_storage_data;
        }else{
            return false;
        }
    }
    
    
    /*
     * 数据导出
     * */
    public function dataexport(){
        /*
         * 人数统计
         * */
        $accessnum='';   //访问总人数
        $appnum='';  //app人数
        $wxnum='';   //微信人数
        $xxnum='';  //线下人数
        /*
         * 线上销量统计
         * */
        $shuiguosucai='';// 水果蔬菜
        $ruoqindanpin=''; //肉禽蛋品
        $haixianshuican='';//海鲜水产
        $ruipindiwen='';//乳品/低温
        $liangyouganhuo='';//粮油干货
        $xiuxianshipin='';//休闲零食
        $jiushuiyinliao='';//酒水饮料
        $gerenhuli='';//个人护理
        $jiajuriyong=''; //家居日用
        $xiawucha='';//下午茶
        $huayi='';//花艺
        
        /*
         * 线下销量统计
         * */
        $shuiguosucai_xx='';// 水果蔬菜
        $ruoqindanpin_xx=''; //肉禽蛋品
        $haixianshuican_xx='';//海鲜水产
        $ruipindiwen_xx='';//乳品/低温
        $liangyouganhuo_xx='';//粮油干货
        $xiuxianshipin_xx='';//休闲零食
        $jiushuiyinliao_xx='';//酒水饮料
        $gerenhuli_xx='';//个人护理
        $jiajuriyong_xx=''; //家居日用
        $xiawucha_xx='';//下午茶
        $huayi_xx='';//花艺
        /*
         * 订单统计
         * */
        $xianshangdingdanliang='';//线上订单量
        $xianshangbaifenbi='';//线上百分比
        $xianxiadingdanliang='';//线下订单量
        $xianxiabaifenbi='';//线下百分比
        $zongdingdanliang='';//总订单量
        
        /*
         * 销售统计
         * */
        
        $xianshangxiaoshoue='';//线上销售额
        $xianshangbaifenbi='';//线上百分比
        $xianxiaxiaoshoue='';//线下销售额
        $xianxiabeifenbi='';//线下百分比
        $kedanjia='';//客单价
        $zongxiaoshoue='';//总销售额
        
        
    }
    
    
    /*
     * 导出当天的订单商品明细数据 
     * */
    public function exprote_orderdetail(){
        set_time_limit(0);
        $dm=I('request.date');
        if(empty($dm)){
            $dm=date('Y-m-d',time());
        }
        $dm=strtotime($dm);
        if($dm===false){
            returnApiError('输入下载对应时间不对');
        }
        $orderdata=M('order_goods_basics')->alias('ogb')
                   ->field('ob.order_sn,ob.add_time,ob.order_type,ob.order_source,ogb.goods_name,ogb.goods_id,ogb.goods_num,ogb.goods_price')
                   ->join(C('DB_PREFIX').'order_basics1 as ob on ob.id=ogb.order_id')
                   ->where('ob.add_time<='.$dm.' or ob.add_time >'.$dm)
                   ->order('ogb.order_id desc')
                   ->select();
       
        if($orderdata){
            $f_head_arr = array(
                "订单号", "下单时间","订单类型", "订单来源","产品名称","货号","数量","单价","小计"
            );
            
            //-/ 请求头部设置
            $title=date('Y-m-d',$dm).'-'.date('His',time());
            $file_name = 'orderdetail'.$title;
            $dirname=date('Y-m-d',$dm);
            $targetFolder='/Public/allgoodsxls/'.$dirname.'/';
            if (!file_exists($_SERVER['DOCUMENT_ROOT'].'/Public')||!is_dir($_SERVER['DOCUMENT_ROOT'].'/Public')){
                mkdir($_SERVER['DOCUMENT_ROOT'].'/Public',0777,true);
            }
            $firstLetterDir=$_SERVER['DOCUMENT_ROOT'].'/Public/allgoodsxls/';
            if (!file_exists($firstLetterDir)||!is_dir($firstLetterDir)){
                mkdir($firstLetterDir,0777,true);
            }
            if (!file_exists($firstLetterDir.'/'.$dirname)||!is_dir($firstLetterDir.'/'.$dirname)){
                mkdir($firstLetterDir.'/'.$dirname,0777,true);
            }
            $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
            $filename=$file_name.'.csv';
            $targetFile = rtrim($targetPath,'/') . '/' .$filename ;
            $file=fopen($targetFile, "wb");
            if(is_file($file)){
                returnApiError('fopen error!');
            }
            foreach ( $f_head_arr as $fkey=>$fval ){
                $f_head_arr[$fkey] = iconv('utf-8', 'gbk', $fval);
            }
            fputcsv($file, $f_head_arr);
            // 计数器
            $cnt = 0;
            // 每隔$limit行，刷新一下输出buffer，不要太大，也不要太小
            $limit = 100000;
            
            foreach ($orderdata as $k=>$v){
                $temp_arr=array();
                $cnt ++;
                if($limit == $cnt){
                    //刷新一下输出buffer，防止由于数据过多造成问题
                    ob_flush();
                    flush();
                    $cnt = 0;
                }
                $oreder_type="";
                $order_source='';
                if($v['order_type']==1){
                    $oreder_type='线上';
                }elseif ($v['order_type']==2){
                    $oreder_type='线下';
                }
                if($v['order_source']==1){
                    $order_source='app';
                }elseif ($v['order_source']==2){
                    $order_source='微信';
                }elseif($v['order_source']==3){
                    $order_source='线下';
                }
                $temp_arr['order_sn'] = iconv('utf-8', 'gbk', "'".$v['order_sn']);
                $temp_arr['add_time'] = iconv('utf-8', 'gbk',date('Y-m-d H:i:s',$v['add_time']));
                $temp_arr['order_type'] = iconv('utf-8', 'gbk',$oreder_type);
                $temp_arr['order_source'] = iconv('utf-8', 'gbk',$order_source);
                $temp_arr['goods_name'] = iconv('utf-8', 'gbk',$v['goods_name']);
                $temp_arr['goods_sn'] = iconv('utf-8', 'gbk',$v['goods_sn']);
                $temp_arr['goods_num'] = iconv('utf-8', 'gbk',$v['goods_num']);
                $temp_arr['goods_price'] = iconv('utf-8', 'gbk',$v['goods_price']);
                $temp_arr['xiaoji'] = iconv('utf-8', 'gbk',$v['goods_price']*$v['goods_num']);
                fputcsv($file, $temp_arr);
                unset($temp_arr);
            }
            unset($goodsdata);
            ob_flush();
            flush();
            
        }
    }
    
    
    /*
     * 导出本月的下单用户信息
     * */
    public function  export_userdata(){
        set_time_limit(0);
        $dm=I('request.date');
        if(empty($dm)){
            $dm=date('Y-m',time());
        }
        $dm=strtotime($dm);
        if($dm===false){
            returnApiError('输入下载对应时间不对');
        }
        $orderdata=M('users_t')->alias('ut')
                   
                   ->join(C('DB_PREFIX').'order_basics1 as ob on ob.user_id=ut.id')
                   ->where('ob.add_time <='.$dm.' or ob.add_time>'.$dm)
                   ->group('ob.user_id')
                   ->order('ob.id')
                   ->select();
        
        if($orderdata){
            $f_head_arr = array(
                "用户名称", "手机号", "收货地址"
            );
            //-/ 请求头部设置
            $title=date('Y-m-d',$dm).'-'.date('His',time());
            $file_name = 'dmorderusers'.$title;
            $dirname=date('Y-m',$dm);
            $targetFolder='/Public/allgoodsxls/'.$dirname.'/';
            if (!file_exists($_SERVER['DOCUMENT_ROOT'].'/Public')||!is_dir($_SERVER['DOCUMENT_ROOT'].'/Public')){
                mkdir($_SERVER['DOCUMENT_ROOT'].'/Public',0777,true);
            }
            $firstLetterDir=$_SERVER['DOCUMENT_ROOT'].'/Public/allgoodsxls/';
            if (!file_exists($firstLetterDir)||!is_dir($firstLetterDir)){
                mkdir($firstLetterDir,0777,true);
            }
            if (!file_exists($firstLetterDir.'/'.$dirname)||!is_dir($firstLetterDir.'/'.$dirname)){
                mkdir($firstLetterDir.'/'.$dirname,0777,true);
            }
            $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
            $filename=$file_name.'.csv';
            $targetFile = rtrim($targetPath,'/') . '/' .$filename ;
            $file=fopen($targetFile, "wb");
            if(is_file($file)){
                returnApiError('fopen error!');
            }
            foreach ( $f_head_arr as $fkey=>$fval ){
                $f_head_arr[$fkey] = iconv('utf-8', 'gbk', $fval);
            }
            fputcsv($file, $f_head_arr);
            // 计数器
            $cnt = 0;
            // 每隔$limit行，刷新一下输出buffer，不要太大，也不要太小
            $limit = 100000;
            
            foreach ($orderdata as $k=>$v){
                $temp_arr=array();
                $cnt ++;
                if($limit == $cnt){
                    //刷新一下输出buffer，防止由于数据过多造成问题
                    ob_flush();
                    flush();
                    $cnt = 0;
                }
                $temp_arr['nickname'] = iconv('utf-8', 'gbk', $v['nickname']);
                $temp_arr['phone'] = iconv('utf-8', 'gbk',$v['phone']);
                $temp_arr['address'] = iconv('utf-8', 'gbk',$v['address']);
                fputcsv($file, $temp_arr);
                unset($temp_arr);
            }
            unset($goodsdata);
            ob_flush();
            flush();
            
        }
        
    }
    
    
    /*
     * 根据订单号批量生成二维码
     * */
    public function batch_barcode(){
        //793283
        header("Content-type: text/html; charset=utf-8");
       /*$vararray=array(
           array("2017082016344717478","合-海珠"),
            array("2017082110320639371","合-海珠"),
            array("2017082112041759426","合-海珠"),
            array("2017082112372041118","合-海珠"),
            array("2017082113044448515","合-海珠"),
            array("2017082114153866476","合-海珠"),
            array("2017082114175922636","合-海珠"),
            array("2017082111381630339","合-海珠"),
            array("2017082111303359196","合-海珠"),
            array("2017082113243645686","合-海珠"),
            array("2017082113420163021","合-海珠"),
            array("2017082114084875684","合-海珠"),
            array("2017082111595642619","合-海珠"),
            array("2017082111595358177","合-海珠"),
            array("2017082112165284381","合-海珠"),
            array("2017082112245359192","合-海珠"),
            array("2017082112150280417","合-海珠"),
            array("2017082020572363459","合-海珠"),
            array("2017082021350143935","合-海珠"),
            array("2017082113164532372","合-海珠"),
            array("2017082011101193501","合-区庄"),
            array("2017082110340428416","合-区庄"),
            array("2017082114071717929","合-区庄"),
            array("2017082100113824793","合-区庄"),
            array("2017082111472310396","合-区庄"),
            array("2017082110393702258","合-区庄"),
            array("2017082113542779910","合-区庄"),
            array("2017082017030013124","合-区庄"),
            array("2017082018012618405","合-区庄"),
            array("2017082111284262166","合-区庄"),
            array("2017082110013314722","合-体育西"),
            array("2017082110253754287","合-体育西"),
            array("2017082111224497325","合-体育西"),
            array("2017082111203438138","合-体育西"),
            array("2017082111554511098","合-体育西"),
            array("2017082113241980353","合-体育西"),
            array("2017082022463855022","合-体育西"),
            array("2017082023190837351","合-体育西"),
            array("2017082113254132762","合-体育西"),
            array("2017082111165486176","合-体育西"),
            array("2017082016242346489","合-越秀荔湾"),
            array("2017082110440797623","合-越秀荔湾"),
            array("2017082110492970955","合-越秀荔湾"),
            array("2017082111122046138","合-越秀荔湾"),
            array("2017082111514872115","合-越秀荔湾"),
            array("2017082113061870887","合-越秀荔湾"),
            array("2017082113183724936","合-越秀荔湾"),
            array("2017082023541998153","合-越秀荔湾"),
            array("2017082100043536811","极-芳村"),
            array("2017082110285609098","极-长湴"),
            array("2017082114281010540","极-长湴"),
            );*/
        $vararray=array(array("2017082011101193501","合-海珠"),
array("2017082100043536811","合-海珠"),
array("2017082110013314722","合-海珠"),
array("2017082110253754287","合-海珠"),
array("2017082110285609098","合-海珠"),
array("2017082111224497325","合-海珠"),
array("2017082111203438138","合-海珠"),
array("2017082111554511098","合-海珠"),
array("2017082113241980353","合-海珠"),
array("2017082022463855022","合-海珠"),
array("2017082023190837351","合-海珠"),
array("2017082113254132762","合-海珠"),
array("2017082016344717478","合-海珠"),
array("2017082110320639371","合-海珠"),
array("2017082112041759426","合-海珠"),
array("2017082112372041118","合-海珠"),
array("2017082113044448515","合-海珠"),
array("2017082114153866476","合-海珠"),
array("2017082114175922636","合-海珠"),
array("2017082111381630339","合-海珠"),
array("2017082111303359196","合-区庄"),
array("2017082113243645686","合-区庄"),
array("2017082113420163021","合-区庄"),
array("2017082114084875684","合-区庄"),
array("2017082111595642619","合-区庄"),
array("2017082111595358177","合-区庄"),
array("2017082112165284381","合-区庄"),
array("2017082112245359192","合-区庄"),
array("2017082112150280417","合-区庄"),
array("2017082110340428416","合-区庄"),
array("2017082114071717929","合-体育西"),
array("2017082100113824793","合-体育西"),
array("2017082111472310396","合-体育西"),
array("2017082110393702258","合-体育西"),
array("2017082113542779910","合-体育西"),
array("2017082114281010540","合-体育西"),
array("2017082016242346489","合-体育西"),
array("2017082110440797623","合-体育西"),
array("2017082110492970955","合-体育西"),
array("2017082111122046138","合-体育西"),
array("2017082111514872115","合-越秀荔湾"),
array("2017082113061870887","合-越秀荔湾"),
array("2017082113183724936","合-越秀荔湾"),
array("2017082111165486176","合-越秀荔湾"),
array("2017082020572363459","合-越秀荔湾"),
array("2017082021350143935","合-越秀荔湾"),
array("2017082113164532372","合-越秀荔湾"),
array("2017082017030013124","合-越秀荔湾"),
array("2017082018012618405","极-芳村"),
array("2017082111284262166","极-长湴"),
array("2017082023541998153","极-长湴")
);
       //dump($vararray);
       //http://www.qinms.com/webapp/barcode/barc.ashx?t1=96&t2=40&t3=3&t4=3&cd=201708171303360043002010   一位条码
         foreach ($vararray as $key=>$val){
                $url='<img src="http://qr.liantu.com/api.php?text='.$val[0].'"> <br />订单号：'.$val[0].'<br /> 划区：'.$val[1].'<br/><br/><br/>';
                  echo $url;
          }
    }
    
    
    /*
     * 强制修复库存记录
     * */
    public function check_goods_storage(){
           $sql='select * from sdx_goods_storage';
           $model = M('goods_storage');
           $list=$model->query($sql);
           foreach ($list as $key=>$val){
               $cache_num=S("goods_practical_num_cache_".$val['goods_id'].'_'.$val['wid']);
               if($cache_num!=$val['practical_num'] && $cache_num-$val['practical_num']==40){
                   $model->where(array('id'=>$val['id']))->setField('practical_num',$cache_num);
                   /*echo $model->getLastSql();
                   dump($val);
                   exit;*/
               }
           }
    }
    
    /*
     *直接出库 
     * 
     */
    public function direct_export(){
        ini_set('max_execution_time', '0');
        set_time_limit(0);
        $sql="SELECT  og.`goods_id`,og.`goods_sn`,og.`goods_name`,SUM(og.`goods_number`) as goods_number_sum FROM ".C ( 'DB_PREFIX' )."bl_order_goods  as og". 
              " LEFT JOIN ".C ( 'DB_PREFIX' )."bl_order_info as oi on oi.order_id =og.order_id".
              " where oi.pay_status=2 AND (oi.add_time+28800)>=UNIX_TIMESTAMP(date_format(now(), '%Y-%m-%d 00:00:00'))".
              " AND (oi.add_time+28800)<UNIX_TIMESTAMP(date_format(now(), '%Y-%m-%d 15:00:00')) AND oi.store_id!=1".
              " GROUP BY og.goods_id";
        /*$sql="SELECT  og.`goods_id`,og.`goods_sn`,og.`goods_name`,SUM(og.`goods_number`) as goods_number_sum FROM ".C ( 'DB_PREFIX' )."bl_order_goods  as og".
            " LEFT JOIN ".C ( 'DB_PREFIX' )."bl_order_info as oi on oi.order_id =og.order_id".
            " where oi.pay_status=2 AND oi.store_id!=1".
            " GROUP BY og.goods_id";*/
        $list=M('')->query($sql);
        if($list){
            $goods_storage_mod=M('goods_storage');
            $take_stock_inventory_record_mod=M('take_stock_inventory_record');
            $goods_storage_record_mod=M('goods_storage_record');
            $take_stock_inventory_record_detail_mod=M('take_stock_inventory_record_detail');
            $wid=16;
            $outbound_type=23;//直接出库-特殊调拨
            $operation_type=6;//特殊调拨
            $source_no=$this->get_batch_sn('ZJ');
            foreach ($list as $k=>$v){
                $gsdata=$goods_storage_mod->where(array('wid'=>$wid,'goods_id'=>$v['goods_id']))->find();
                if($gsdata){
                    $cache_goods_practical_num = get_goods_practical_num_cache($v['goods_id'],$wid,$gsdata['practical_num']);
                    //获取队列库存缓存
                    $cache_queue_goods_stock = get_queue_goods_stock($v['goods_id'],$wid);
                    if($gsdata['practical_num']>0 && $v['goods_number_sum']<=$gsdata['practical_num']){
                        $data=array(
                            'practical_num'=>$gsdata['practical_num']-$v['goods_number_sum']
                        );
                        $flag = $goods_storage_mod->where(array('goods_id'=>$v['goods_id'],'wid'=>$wid))->save($data);
                        if($flag){
                            //更新实际库存缓存
                            set_goods_practical_num_cache($v['goods_id'],$wid,$cache_goods_practical_num-$v['goods_number_sum']);
                            //更新队列库存缓存
                            set_queue_goods_stock($v['goods_id'],$wid,$cache_queue_goods_stock-$v['goods_number_sum']);
                        }
                        $gsrdata=array(
                            'goods_storage_id'=>$gsdata['id'],
                            'wpid'=>0,
                            'goods_id'=>$v['goods_id'],
                            'goods_sn'=>$v['goods_sn'],
                            'operation_num'=>$v['goods_number_sum'],
                            'real_num'=>$gsdata['practical_num']-$v['goods_number_sum'],
                            'frozen_num'=>0,
                            'defective_num'=>0,
                            'operation_userid'=>0,
                            'operation_addtime'=>gmtime(),
                            'source_no'=>$source_no,
                            'record_type'=>$outbound_type,//直接出库-特殊调拨
                            'remark'=>'直接出库-特殊调拨'
                        );
                        $goods_storage_record_mod->add($gsrdata);
                        $tsirlist=$take_stock_inventory_record_mod->where(array('batch_sn'=>$source_no))->find();
                        if($tsirlist){
                            $tsirddata=array(
                                'tsir_id'=>$tsirlist['id'],
                                'batch_sn'=>$tsirlist['batch_sn'],
                                'goods_storage_id'=>$gsdata['id'],
                                'wid'=>$gsdata['wid'],
                                'goods_id'=>$v['goods_id'],
                                'goods_sn'=>$v['goods_sn'],
                                'goods_name'=>$v['goods_name'],
                                'add_time'=>gmtime(),
                                'operation_type'=>$operation_type,
                                'take_stock_num'=>$v['goods_number_sum'],
                                'real_num'=>$gsdata['practical_num']-$v['goods_number_sum'],
                            );
                            //生成盘点记录明细
                            $tsirdid=$take_stock_inventory_record_detail_mod->add($tsirddata);
                        }else{
                            $tsirdata=array(
                                'batch_sn'=>$source_no,
                                'operation_userid'=>0,
                                'operation_addtime'=>gmtime(),
                                'backflow_documents_pic'=>'',
                                'documents_remark'=>'系统直接出库'
                            );
                            //生成盘点记录
                            $tsirid=$take_stock_inventory_record_mod->add($tsirdata);
                            if($tsirid){
                                $tsirddata=array(
                                    'tsir_id'=>$tsirid,
                                    'batch_sn'=>$source_no,
                                    'goods_storage_id'=>$gsdata['id'],
                                    'wid'=>$gsdata['wid'],
                                    'goods_id'=>$v['goods_id'],
                                    'goods_sn'=>$v['goods_sn'],
                                    'goods_name'=>$v['goods_name'],
                                    'add_time'=>gmtime(),
                                    'operation_type'=>$operation_type,
                                    'take_stock_num'=>$v['goods_number_sum'],
                                    'real_num'=>$gsdata['practical_num']-$v['goods_number_sum'],
                                );
                                 
                                //生成盘点记录明细
                                $tsirdid=$take_stock_inventory_record_detail_mod->add($tsirddata);
                            }
                        }
                    }else{
                        continue;
                    }
                }else{
                    continue;
                }
                
            }
        }
    }
    
    /*
     * 生成批次号
     * */
    private function get_batch_sn($prefix){
        /* 选择一个随机的方案 */
        mt_srand((double) microtime() * 1000000);
         
        return $prefix.date('YmdHis') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
    }


    /**
     *  指定仓库商品进行系统盘点
     */
    public function system_inventory(){

        header("Content-type: text/html; charset=utf-8");
        set_time_limit(0);
        import('Org.Util.PHPExcel');
        import("Org.Util.PHPExcel.Reader.Excel5");
        //import('Org.Util.PHPExcel.IOFactory');
        $wid=I('request.wid');
       // $datemd=I('request.md');
        //$datemd=$datemd-28800;

        if(empty($wid)){
            die('no wid!');
        }

        $targetFolder='/Public/systeminventory/';
        if (!file_exists($_SERVER['DOCUMENT_ROOT'].'/Public')||!is_dir($_SERVER['DOCUMENT_ROOT'].'/Public')){
            mkdir($_SERVER['DOCUMENT_ROOT'].'/Public',0777,true);
        }
        if (!file_exists($_SERVER['DOCUMENT_ROOT'].'/Public/systeminventory')||!is_dir($_SERVER['DOCUMENT_ROOT'].'/Public/systeminventory')){
            mkdir($_SERVER['DOCUMENT_ROOT'].'/Public/systeminventory',0777,true);
        }
        $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
        $filename='systeminventory.xls';
        $targetFile = rtrim($targetPath,'/') . '/' .$filename ;
        $PHPReader = new \PHPExcel_Reader_Excel5();

        if (!file_exists($targetFile)) {
            die('no file!');
        }
        //载入文件
        $PHPExcel = $PHPReader->load($targetFile);
        //获取表中的第一个工作表，如果要获取第二个，把0改为1，依次类推
        $currentSheet=$PHPExcel->getActiveSheet();
        // $currentSheet = $PHPExcel->getSheet(0);
        //    $allColumn = $currentSheet->getHighestColumn();  //获取总列数
        $allRow = $currentSheet->getHighestRow();  //获取总行数

        //导入PHPExcel.Shared.Date 用以处理时间类型

        //循环获取表中的数据,
        $goods_storage_mod=M('goods_storage');
        //$goods_storage_record_mod=M('goods_storage_record');
        $source_no=$this->get_batch_sn('PD');
        for ($Row = 2; $Row <= $allRow; $Row++) {
            echo $Row."=>";
            $goods_sn=$currentSheet->getCell('A' . $Row)->getValue();  //商品货号
            $goods_sn=trim(str_replace("`","",$goods_sn));
            $goods_name=$currentSheet->getCell('B' . $Row)->getValue(); // 商品名称
            $real_numbers=$currentSheet->getCell('C' . $Row)->getValue(); //盘点实数
            if(strlen($real_numbers)<=0){
                echo 'ERROR=>该货号：'.$goods_sn.'<br />实数没有录入';
                continue;
            }
            $goods_storage_data=$this->check_goods_storage_exists($goods_sn,$wid);

            if(!$goods_storage_data){
                echo 'ERROR=>查无此货号：'.$goods_sn.'<br />';
                continue;
            }

           // $sum=$goods_storage_record_mod->where(array('goods_id'=>$goods_storage_data['goods_id'],'wid'=>$goods_storage_data['wid'],'operation_addtime'=>array('EGT',$datemd),'record_type'=>array('NEQ',33)))->sum('operation_num');
            //$real_numbers=$real_numbers-$sum;
            $gssave=$goods_storage_mod->where(array('goods_id'=>$goods_storage_data['goods_id'],'wid'=>$goods_storage_data['wid']))->save(array('practical_num'=>$real_numbers,'freeze_num'=>0));
            //更新实际库存缓存
            set_goods_practical_num_cache($goods_storage_data['goods_id'],$goods_storage_data['wid'],$real_numbers);
            //更新队列库存缓存
            set_queue_goods_stock($goods_storage_data['goods_id'],$goods_storage_data['wid'],$real_numbers);
            if($gssave!==false){
                $goodsrecord=array(
                    'goods_storage_id'=>$goods_storage_data['goods_storage_id'],
                    'wpid'=>0,
                    'wid'=>$goods_storage_data['wid'],
                    'goods_id'=>$goods_storage_data['goods_id'],
                    'goods_sn'=>$goods_storage_data['goods_sn'],
                    'operation_num'=>$real_numbers,
                    'real_num'=>$real_numbers,
                    'frozen_num'=>0,
                    'defective_num'=>0,
                    'operation_userid'=>0,
                    'average_userid'=>0,
                    'operation_addtime'=>gmtime(),
                    'source_no'=>$source_no,
                    'record_type'=>33,  //系统盘点
                    'remark'=>'通过Excel系统盘点',
                );
                //商品出入库记录
                D('Goodsstoragerecord')->add_storage_record($goodsrecord);
                $goodsfreezerecord=array(
                    'goods_storage_id'=>$goods_storage_data['goods_storage_id'],
                    'wid'=>$goods_storage_data['wid'],
                    'goods_id'=>$goods_storage_data['goods_id'],
                    'goods_sn'=>$goods_storage_data['goods_sn'],
                    'goods_name'=>$goods_storage_data['goods_name'],
                    'freeze_num'=>0,// 强制归零
                    'real_num'=>0,
                    'frozen_num'=>0,
                    'defective_num'=>0,
                    'operation_userid'=>0,
                    'average_userid'=>0,
                    'operation_addtime'=>gmtime(),
                    'source_no'=>$source_no,
                    'record_type'=>13,
                    'remark'=>'通过Excel系统盘点',
                );
                //商品冻结出入记录
                D('Goodsfreezerecord')->add_freeze_record($goodsfreezerecord);
            }else{
                echo 'ERROR=>盘点此货号：'.$goods_sn.'失败！<br />';
                continue;
            }
        }

    }

    //删除订单自动取消重复的实际出入库记录和冻结出入库记录
    public function delautocancelorderrecord(){
        header("Content-type: text/html; charset=utf-8");
        set_time_limit(0);
        $wid=I('request.wid');
        if(empty($wid)){
            die('wid null');
            exit;
        }
        $start=I('request.start');
        if(empty($start)){
            die('start null');
            exit;
        }
        $end=I('request.end');
        if(empty($end)){
            die('end null');
            exit;
        }
        $sql="SELECT oi.order_sn,og.goods_id,og.goods_sn,oi.wid FROM `sdx_order_goods` as og LEFT JOIN `sdx_order_info` as oi on og.`order_id` =oi.`order_id`  WHERE oi.`order_status` =2 AND oi.`pay_status` =0 AND oi.`shipping_status` =0 AND oi.`to_buyer` ='支付超时自动取消' AND oi.`add_time` >=".$start." AND oi.`add_time` <".$end." and oi.`wid` =".$wid;
        $list=M('')->query($sql);
        if($list){
            foreach ($list as $k=>$v){
                $del_gsr_wheres="record_type=6 and source_no='".$v['order_sn']."' and wid=".$v['wid']." and goods_id=".$v['goods_id'];
                $select_gsr_sql='select id from sdx_goods_storage_record where '.$del_gsr_wheres;
                $listgoods_gsr=M('')->query($select_gsr_sql);
                if($listgoods_gsr){
                    $ids=array();
                    foreach ($listgoods_gsr as $key=>$val){
                        if($key==0){
                            continue;
                        }
                        $ids[]=$val['id'];
                    }
                    if(count($ids)>0){
                        $del_gsr_sql="delete from sdx_goods_storage_record where id in(".implode(',',$ids).")";
                        M('')->execute($del_gsr_sql);
                    }
                    unset($ids);
                    unset($listgoods_gsr);
                }
                $del_gfr_wheres="record_type=5 and source_no='".$v['order_sn']."' and wid=".$v['wid']." and goods_id=".$v['goods_id'];
                $select_gfr_sql='select id from sdx_goods_freeze_record where '.$del_gfr_wheres;
                $listgoods_gfr=M('')->query($select_gfr_sql);
                if($listgoods_gfr){
                    $ids=array();
                    foreach ($listgoods_gfr as $key=>$val){
                        if($key==0){
                            continue;
                        }
                        $ids[]=$val['id'];
                    }
                    if(count($ids)>0) {
                        $del_gfr_sql = "delete from sdx_goods_freeze_record where id in(" . implode(',', $ids) . ")";
                        M('')->execute($del_gfr_sql);
                    }
                    unset($ids);
                    unset($listgoods_gfr);
                }
            }
            returnApiSuccess(1);
        }else{
            returnApiError('查无数据');
        }
    }
}